package com.zjl.学习.第06章_块步骤_读操作写.spring;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.zjl.springbatch.util.OutColour;
import com.zjl.学习.第06章_块步骤_读操作写.User;
import org.springframework.batch.core.*;
import org.springframework.batch.core.configuration.annotation.EnableBatchProcessing;
import org.springframework.batch.core.configuration.annotation.JobBuilderFactory;
import org.springframework.batch.core.configuration.annotation.StepBuilderFactory;
import org.springframework.batch.core.launch.JobLauncher;
import org.springframework.batch.core.launch.support.RunIdIncrementer;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.skip.SkipLimitExceededException;
import org.springframework.batch.core.step.skip.SkipPolicy;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.item.ExecutionContext;
import org.springframework.batch.item.ItemReader;
import org.springframework.batch.item.ItemWriter;
import org.springframework.batch.item.database.JdbcCursorItemReader;
import org.springframework.batch.item.database.JdbcPagingItemReader;
import org.springframework.batch.item.database.PagingQueryProvider;
import org.springframework.batch.item.database.builder.JdbcCursorItemReaderBuilder;
import org.springframework.batch.item.database.builder.JdbcPagingItemReaderBuilder;
import org.springframework.batch.item.database.support.SqlPagingQueryProviderFactoryBean;
import org.springframework.batch.item.file.FlatFileItemReader;
import org.springframework.batch.item.file.builder.FlatFileItemReaderBuilder;
import org.springframework.batch.item.json.JacksonJsonObjectReader;
import org.springframework.batch.item.json.JsonItemReader;
import org.springframework.batch.item.json.builder.JsonItemReaderBuilder;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.io.ClassPathResource;
import org.springframework.jdbc.core.ArgumentPreparedStatementSetter;

import javax.sql.DataSource;
import java.nio.charset.Charset;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Configuration
@ComponentScan
@EnableBatchProcessing
public class A_Item_Spring {

    @Autowired
    private JobBuilderFactory jobBuilderFactory;
    @Autowired
    private StepBuilderFactory stepBuilderFactory;

    @Bean
    public FlatFileItemReader<User> userItemReader(){
        return new FlatFileItemReaderBuilder<User>()
                .name("userItemReader")
                .resource(new ClassPathResource("item/user.txt"))  //指定读取的文件
                .delimited().delimiter("#")  //读取出一行数据，该如何分割数据，默认以,分割，当前使用#号分割
                .names("id", "name", "age")//给分割后数据打name标记，后续跟User对象属性进行映射
                .targetType(User.class)      //读取出一行数据封装成什么对象
                .build();
    }


    @Bean//加注解会每次都会抛错，因为Bean在启动时就会执行
    public FlatFileItemReader<User> ItemReadError() throws Exception {
            return new FlatFileItemReaderBuilder<User>()
                    .name("userItemReader")
                    .resource(new ClassPathResource("item/userxxx.txt"))  //指定读取的文件
                    .delimited().delimiter("#")  //读取出一行数据，该如何分割数据，默认以,分割，当前使用#号分割
                    .names("id", "name", "age")//给分割后数据打name标记，后续跟User对象属性进行映射
                    .targetType(User.class)      //读取出一行数据封装成什么对象
                    .build();
        }

    @Bean
    public ItemWriter<User> itemWriter(){
        return new ItemWriter<User>() {
            @Override
            public void write(List<? extends User> items) throws Exception {
                OutColour.out.printlnRed(items + "个数：" + items.size());
            }
        };
    }
    @Bean//任务 Tasklet 这是最简单的    还有Chunk块处理
    public Tasklet tasklet05A(){
        return new Tasklet() {
            @Override
            public RepeatStatus execute(StepContribution contribution, ChunkContext chunkContext) throws Exception {
                StepExecution stepExecution = chunkContext.getStepContext().getStepExecution();
                ExecutionContext executionContext = chunkContext.getStepContext().getStepExecution().getExecutionContext();
                executionContext.put("xx","xx");//放入shep的共享变量

                if(true) throw new Exception("测试");

                chunkContext.getStepContext().getStepExecution().setTerminateOnly();//设置 此操作状态为   STOPPED  //表示已完成的加工 中断状态停止
                OutColour.out.printlnRed("****************A*******************");
                return RepeatStatus.FINISHED;//已完成
            }
        };
    }

    @Bean
    public Step stepItemError1() throws Exception {
        return stepBuilderFactory
                .get("stepItemError1")
                .tasklet(tasklet05A())
                .build();
    }

    @Bean
    public Job jobItem() throws Exception {
        return jobBuilderFactory.get("jobItem4")
                .start(stepItemError1())
                .incrementer(new RunIdIncrementer())
                .build();
    }

    public static void main(String[] args) {
        System.setProperty("spring.profiles.active","01");//  同理 --spring.profiles.active=xxx
        ApplicationContext context =
                new AnnotationConfigApplicationContext(A_Item_Spring.class);
        System.out.println("***********启动完毕**当前编码:" + Charset.defaultCharset().name() + "****************");
        JobLauncher jobLauncher = context.getBean(JobLauncher.class);
        Job job = context.getBean(Job.class);
        JobExecution execution = null;
        try {
             execution = jobLauncher.run(job, new JobParameters());
            OutColour.out.printlnGreen("Job Execution Status : " , execution.getStatus());
            if(execution.getStatus() == BatchStatus.COMPLETED) {
                OutColour.out.printlnGreen(execution.getStatus());
            }
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
}

